package com.epoch.wx.service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.epoch.wx.dao.WxToken;
import com.epoch.wx.util.CharUtil;

public class TokenService {
	
	/**
	 * 24小时后过期
	 */
	private final static int EXPIRE = 3600 * 24;
	
	public static final TokenService me = new TokenService();
	
	private TokenService() {
		
	}
	
	public Map<String, Object> createToken(String userId) {
		//生成一个token
        String token = CharUtil.getRandomString(32);
        //当前时间
        Date now = new Date();
        //过期时间
        Date expireTime = new Date(now.getTime() + EXPIRE * 1000);
        WxToken wxToken = WxToken.dao.findById(userId);
        if(null == wxToken) {
        	wxToken = new WxToken();
            wxToken.set(WxToken.USER_ID, userId);
            wxToken.set(WxToken.TOKEN, token);
            wxToken.set(WxToken.EXPIRE_TIME, expireTime);
            wxToken.save();
        }else {
        	wxToken.set(WxToken.TOKEN, token);
            wxToken.set(WxToken.EXPIRE_TIME, expireTime);
            wxToken.update();
        } 
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("expire", EXPIRE);
        return map;
	}
}
